<script lang="ts" setup>
const props = defineProps({
  flag: {
    type: Number,
    required: true
  },
  dataresources: {
    type: Array,
    required: false
  }
});

const emit = defineEmits([
  'update:dataselected',
  'update:taskselected',
  'update:params',
  'item-selected'
]);

interface HeaderItem {
  title: string;
  key: string;
  align: string;
  sortable?: boolean;
}

const title1 = [
  { title: '状态', key: 'status', align: 'center' },
  { title: '集群类型', key: 'cluster_type', align: 'center' },
  { title: '集群域', key: 'cluster_region', align: 'center' },
  { title: 'CPU资源使用量(cores)', key: 'cpuuse', align: 'center' },
  { title: 'CPU资源总量(cores)', key: 'cputotal', align: 'center' },
  { title: 'GPU资源使用量(num)', key: 'gpuuse', align: 'center' },
  { title: 'GPU资源总量(num)', key: 'gputotal', align: 'center' },
  { title: '内存资源使用量(MB)', key: 'memuse', align: 'center' },
  { title: '内存资源总量(MB)', key: 'memtotal', align: 'center' },
  { title: '硬盘存储使用量(MB)', key: 'diskuse', align: 'center' },
  { title: '硬盘存储总量(MB)', key: 'disktotal', align: 'center' },
  { title: '任务数', key: 'task', align: 'center' }
];

const title2 = [
  { title: '任务状态', key: 'totalstatus', align: 'center' },
  {
    title: '任务状态(active/succeed/failed)',
    key: 'taskstate',
    align: 'center'
  },
  { title: '运行任务数', key: 'runtask', align: 'center' },
  { title: '任务总数', key: 'tasktotal', align: 'center' },
  { title: 'CPU资源使用量(cores)', key: 'cpuuse', align: 'center' },
  { title: 'GPU资源使用量(num)', key: 'gpuuse', align: 'center' },
  { title: '内存资源使用量(MB)', key: 'memuse', align: 'center' }
];

const title3 = [
  { title: 'CPU资源使用量(cores)', key: 'cpuuse', align: 'center' },
  { title: 'CPU资源总量(cores)', key: 'cputotal', align: 'center' },
  { title: 'GPU资源使用量(num)', key: 'gpuuse', align: 'center' },
  { title: 'GPU资源总量(num)', key: 'gputotal', align: 'center' },
  { title: '内存资源使用量(MB)', key: 'memuse', align: 'center' },
  { title: '内存资源总量(MB)', key: 'memtotal', align: 'center' },
  { title: '硬盘存储使用量(MB)', key: 'diskuse', align: 'center' },
  { title: '硬盘存储总量(MB)', key: 'disktotal', align: 'center' }
];

const title4 = [
  { title: '所在集群名', key: 'cluster_name', align: 'center' },
  { title: '任务状态', key: 'task_phase', align: 'center' },
  { title: '任务副本数', key: 'task_replica', align: 'center' },
  { title: 'CPU资源使用量(cores)', key: 'cpu_total_usage', align: 'center' },
  { title: 'GPU资源使用量(num)', key: 'gpu_total_usage', align: 'center' },
  { title: '内存资源使用量(MB)', key: 'memory_total_usage', align: 'center' },
  { title: '创建时间', key: 'create_at', align: 'center' },
  { title: '运行时间(s)', key: 'duration', align: 'center' }
];

const itemsPerPage = ref(10);
const search = ref('');
const loading = ref(true);
const totalItems = ref(0);

const computedHeaders = computed<HeaderItem[]>(() => {
  if (props.flag === 0) {
    return [
      {
        title: '集群名',
        align: 'center',
        sortable: false,
        key: 'name',
        value: 'name'
      },
      ...title1.map((header) => {
        if (header.key === 'cluster_type') {
          return {
            ...header,
            sortable: true, // 启用排序

            sort: (a: any, b: any) => {
              const order = { cloud: 1, edge: 2, device: 3 };
              return (order[a] || 4) - (order[b] || 4);
            }
          };
        }
        return header;
      })
    ];
  } else if (props.flag === 1) {
    return [
      {
        title: '任务名',
        align: 'start',
        sortable: false,
        key: 'name',
        value: 'name'
      },
      ...title2
    ];
  } else if (props.flag === 2) {
    return [
      {
        title: '节点地址',
        align: 'center',
        sortable: true,
        key: 'node_address',
        value: 'node_address'
      },
      ...title3
    ];
  } else if (props.flag === 3) {
    return [
      {
        title: '任务名',
        align: 'center',
        sortable: false,
        key: 'task_name',
        value: 'task_name'
      },
      ...title4
    ];
  } else {
    // 默认返回
    return [];
  }
});

// 模拟 API
const FakeAPI = {
  async fetch({ page, itemsPerPage, sortBy }) {
    return new Promise((resolve) => {
      setTimeout(() => {
        const start = (page - 1) * itemsPerPage;
        const end = start + itemsPerPage;
        let items = [...props.dataresources];

        if (!sortBy.length) {
          const order = { cloud: 1, edge: 2, device: 3 };
          items.sort((a, b) => {
            const aValue = order[a.cluster_type] || 4;
            const bValue = order[b.cluster_type] || 4;
            return aValue - bValue;
          });
        } else {
          const sortKey = sortBy[0].key;
          const sortOrder = sortBy[0].order;
          items.sort((a, b) => {
            const aValue = a[sortKey];
            const bValue = b[sortKey];
            return sortOrder === 'desc' ? bValue - aValue : aValue - bValue;
          });
        }

        const paginated = items.slice(start, end);
        resolve({ items: paginated, total: items.length });
      }, 0);
    });
  }
};

function loadItems({
  page,
  itemsPerPage,
  sortBy = [{ key: 'cluster_type', order: 'asc' }]
}) {
  loading.value = true;
  console.log('sortBy:', sortBy); // Debug 输出排序参数
  FakeAPI.fetch({ page, itemsPerPage, sortBy }).then(({ items, total }) => {
    // 直接将 paginated items 赋值给 dataresources
    props.dataresources = [...items]; // 用 items 替换 dataresources 中的内容
    totalItems.value = total;
    loading.value = false;
  });
}

function updateTableOptions(options: any) {
  const { page, itemsPerPage, sortBy } = options;
  loadItems({ page, itemsPerPage, sortBy });
}

loadItems({ page: 1, itemsPerPage: itemsPerPage.value });

function handleClick(id: string) {
  console.log(id);
  emit('item-selected', { value: id });
}

function getstatusColor(status: boolean): string {
  console.log('Task submitted successfully:', status);
  if (status == false) return 'red';
  else if (status == true) return 'green';
  else return 'orange';
}

function gettotalstatusColor(totalstatus: string): string {
  if (totalstatus == 'failed') return 'red';
  else if (totalstatus == 'running') return 'green';
  else return 'orange';
}

function getcluster_typeColor(cluster_type: string): string {
  if (cluster_type == 'cloud') return 'blue';
  else if (cluster_type == 'edge') return 'green';
  else return 'orange';
}

function gettask_phaseColor(task_phase: string): string {
  const color = ref('');
  switch (task_phase) {
    case 'CentralSubmitted':
    case 'CentralWrapData':
    case 'CentralScheduled':
    case 'CentralDispatch':
    case 'ClusterCreated':
      color.value = 'blue';
      break;
    case 'ClusterPending':
      color.value = 'yellow';
      break;
    case 'ClusterRunning':
    case 'ClusterCompleted':
      color.value = 'green';
      break;
    case 'ClusterFailed':
    case 'Unknown':
      color.value = 'red';
      break;
    default:
      color.value = 'grey';
      break;
  }
  return color.value;
}

function gettask_phaseText(task_phase: string): string {
  const text = ref('');
  switch (task_phase) {
    case 'CentralSubmitted':
      text.value = '任务已提交到中央';
      break;
    case 'CentralWrapData':
      text.value = '中央包装数据中';
      break;
    case 'CentralScheduled':
      text.value = '中央调度中';
      break;
    case 'CentralDispatch':
      text.value = '中央分发中';
      break;
    case 'ClusterCreated':
      text.value = '任务已于集群创建';
      break;
    case 'ClusterPending':
      text.value = '任务于集群挂起';
      break;
    case 'ClusterRunning':
      text.value = '任务运行中';
      break;
    case 'ClusterCompleted':
      text.value = '任务已完成';
      break;
    case 'ClusterFailed':
      text.value = '任务失败';
      break;
    case 'Unknown':
      text.value = '未知状态';
      break;
    default:
      text.value = '未知状态';
      break;
  }
  return text.value;
}
</script>

<template>
  <v-data-table
    v-if="props.flag == 0"
    v-model:items-per-page="itemsPerPage"
    class="custom-table"
    :headers="computedHeaders"
    :items="dataresources"
    :items-length="totalItems"
    :loading="loading"
    :search="search"
    item-value="name"
    item-key="id"
    :show-select="false"
    select-strategy="single"
    return-object
    @update:options="updateTableOptions"
  >
    <template #item.name="{ item }">
      <div class="flex items-center">
        <NuxtLink :to="`/cluster/node/${item.id}`">
          {{ item.name }}
        </NuxtLink>
      </div>
    </template>
    <template #item.cluster_type="{ item }">
      <div class="flex items-center">
        <v-chip :color="getcluster_typeColor(item.cluster_type)">
          {{
            item.cluster_type === 'cloud'
              ? '云集群'
              : item.cluster_type === 'edge'
                ? '边集群'
                : item.cluster_type === 'device'
                  ? '端设备'
                  : item.cluster_type
          }}
        </v-chip>
      </div>
    </template>

    <template #item.status="{ item }">
      <div class="flex items-center">
        <v-chip :color="getstatusColor(item.status)">
          {{ item.status === true ? '正常' : '异常' }}
        </v-chip>
      </div>
    </template>

    <template #item.cpuuse="{ item }">
      {{ item.cpuuse.toFixed(2) }}
    </template>
    <template #item.cputotal="{ item }">
      {{ item.cputotal.toFixed(2) }}
    </template>
    <template #item.gpuuse="{ item }">
      {{ item.gpuuse.toFixed(2) }}
    </template>
    <template #item.gputotal="{ item }">
      {{ item.gputotal.toFixed(2) }}
    </template>
    <template #item.memuse="{ item }">
      {{ item.memuse.toFixed(2) }}
    </template>
    <template #item.memtotal="{ item }">
      {{ item.memtotal.toFixed(2) }}
    </template>
    <template #item.diskuse="{ item }">
      {{ item.diskuse.toFixed(2) }}
    </template>
    <template #item.disktotal="{ item }">
      {{ item.disktotal.toFixed(2) }}
    </template>
  </v-data-table>

  <v-data-table
    v-else-if="props.flag == 1"
    v-model:items-per-page="itemsPerPage"
    :headers="computedHeaders"
    :items="dataresources"
    :items-length="totalItems"
    :loading="loading"
    :search="search"
    item-value="name"
    item-key="id"
    :show-select="false"
    select-strategy="single"
    return-object
    @update:options="updateTableOptions"
  >
    <template #item.name="{ item }">
      <div class="flex items-center">
        <v-btn
          variant="text"
          class="justify-start"
          silm="true"
          @click="handleClick(item.id)"
          v-text="item.name"
        />
      </div>
    </template>
    <template #item.totalstatus="{ item }">
      <div class="flex items-center">
        <v-chip :color="gettotalstatusColor(item.totalstatus)">
          {{ item.totalstatus === 'running' ? '运行' : '失败' }}
        </v-chip>
      </div>
    </template>
    <template #item.cpuuse="{ item }">
      {{ item.cpuuse.toFixed(2) }}
    </template>
    <template #item.gpuuse="{ item }">
      {{ item.gpuuse.toFixed(2) }}
    </template>
    <template #item.memuse="{ item }">
      {{ item.memuse.toFixed(2) }}
    </template>
  </v-data-table>
  <v-data-table
    v-else-if="props.flag == 2"
    v-model:items-per-page="itemsPerPage"
    :headers="computedHeaders"
    :items="dataresources"
    :items-length="totalItems"
    :loading="loading"
    :search="search"
    item-value="name"
    item-key="id"
    @update:options="updateTableOptions"
  >
    <template #item.cpuuse="{ item }">
      {{ item.cpuuse.toFixed(2) }}
    </template>
    <template #item.cputotal="{ item }">
      {{ item.cputotal.toFixed(2) }}
    </template>
    <template #item.gpuuse="{ item }">
      {{ item.gpuuse.toFixed(2) }}
    </template>
    <template #item.gputotal="{ item }">
      {{ item.gputotal.toFixed(2) }}
    </template>
    <template #item.memuse="{ item }">
      {{ item.memuse.toFixed(2) }}
    </template>
    <template #item.memtotal="{ item }">
      {{ item.memtotal.toFixed(2) }}
    </template>
    <template #item.diskuse="{ item }">
      {{ item.diskuse.toFixed(2) }}
    </template>
    <template #item.disktotal="{ item }">
      {{ item.disktotal.toFixed(2) }}
    </template>
  </v-data-table>
  <v-data-table
    v-else
    v-model:items-per-page="itemsPerPage"
    :headers="computedHeaders"
    :items="dataresources"
    :items-length="totalItems"
    :loading="loading"
    :search="search"
    item-value="task_name"
    item-key="task_name"
    @update:options="updateTableOptions"
  >
    <template #item.task_phase="{ item }">
      <div class="flex items-center">
        <v-chip :color="gettask_phaseColor(item.task_phase)">
          {{ gettask_phaseText(item.task_phase) }}
        </v-chip>
      </div>
    </template>
    <template #item.cpu_total_usage="{ item }">
      {{ item.cpu_total_usage.toFixed(2) }}
    </template>
    <template #item.gpu_total_usage="{ item }">
      {{ item.gpu_total_usage.toFixed(2) }}
    </template>
    <template #item.memory_total_usage="{ item }">
      {{ item.memory_total_usage.toFixed(2) }}
    </template>
  </v-data-table>
</template>

<style scoped>
.custom-table /deep/ .v-data-table__th {
  font-size: 13px;
}
</style>
